#!/usr/bin/env python3

import subprocess
import tempfile

def assemble_and_disassemble(assembly_instruction, address):
    # Create a temporary assembly file
    with tempfile.NamedTemporaryFile(suffix='.s', delete=False) as asm_file:
        asm_file.write(f".section .text\n.global _start\n_start:\n    {assembly_instruction}\n".encode())
        asm_filename = asm_file.name

    # Assemble the assembly file to an object file
    obj_filename = asm_filename.replace('.s', '.o')
    subprocess.run(['riscv64-unknown-elf-as', '-o', obj_filename, asm_filename])

    # Disassemble the object file to get the machine code
    result = subprocess.run(['riscv64-unknown-elf-objdump', '-d', obj_filename], capture_output=True, text=True)

    # Extract the machine code from the objdump output
    lines = result.stdout.splitlines()
    for line in lines:
        if '_start' in line:
            # The next line contains the machine code and address
            machine_code_line = lines[lines.index(line) + 1]
            parts = machine_code_line.split()
            machine_code = parts[1]
            return f"{address:08x}:{machine_code} \\t{spli_instruction(assembly_instruction)}\\n"

    return None

def spli_instruction(assembly_instruction):
    # Split the instruction and operands by the first space
    parts = assembly_instruction.split(' ', 1)
    if len(parts) > 1:
        return f"{parts[0]}\\t{parts[1]}"
    return assembly_instruction

def main():
    address = 0x00000000
    while True:
        assembly_instruction = input("Enter the RISC-V assembly instruction: ")
        machine_code = assemble_and_disassemble(assembly_instruction, address)
        if machine_code:
            print(f"Output: {machine_code}")
            address += 4
        else:
            print("Failed to assemble the instruction.")


if __name__ == "__main__":
    main()
